const apiHost: string = 'http://localhost:4050/';
// const apiHost: string = 'https://zh-ser.gocau.com';

// requestUtil.ts
function request(url: string, method: string, data: any = {}, header: any = {}): Promise<any> {
  const app = getApp<IAppOption>();
  // Returns a Promise object
  return new Promise((resolve, reject) => {
    wx.request({
      url: apiHost + url, // Server API address
      method: method, // Request method
      data: data, // Data to send
      header: {
        'token':app.globalData.token,
        'plat':'app',
        'content-type': 'application/json', // Default value
        ...header // Allow custom request headers
      },
      success(res) {
        // Success handling
        if (res.statusCode === 200) {
          resolve(res.data.data); // Resolve successful callback
        } else {
          reject(res); // Considered as failure when status code is not 200
        }
      },
      fail(error) {
        // Failure handling
        reject(error);
      }
    });
  });
}

// Encapsulate GET request
function getRequest(url: string, data: any = {}, header: any = {}): Promise<any> {
  return request(url, 'GET', data, header);
}

// Encapsulate POST request
function postRequest(url: string, data: any = {}, header: any = {}): Promise<any> {
  return request(url, 'POST', data, header);
}

export {
  getRequest,
  postRequest
};
